package cn.sh.yhk.configure.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.session.HttpSessionEventPublisher;

import javax.annotation.Resource;

/**
 * Created with IDEA
 * author:Yhk
 * Date:2019/1/9
 * Time:11:25 AM
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)  //  启用方法级别的权限认证
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    /**
     * 未登陆时返回 JSON 格式的数据给前端（否则为 html）
     */
    @Resource
    AjaxAuthenticationEntryPoint authenticationEntryPoint;
    /**
     * 登录成功返回的 JSON 格式数据给前端（否则为 html）
     */
    @Resource
    AjaxAuthenticationSuccessHandler authenticationSuccessHandler;

    /**
     * 登录失败返回的 JSON 格式数据给前端（否则为 html）
     */
    @Resource
    AjaxAuthenticationFailureHandler authenticationFailureHandler;
    /**
     * 注销成功返回的 JSON 格式数据给前端（否则为 登录时的 html）
     */
    @Resource
    AjaxLogoutSuccessHandler logoutSuccessHandler;
    /**
     * 无权访问返回的 JSON 格式数据给前端（否则为 403 html 页面）
     */
    @Resource
    AjaxAccessDeniedHandler accessDeniedHandler;
    /**
     * 用户认证操作
     */
    @Resource
    private SecurityUserAuthor securityUserAuthor;

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //单用户登录，如果有一个登录登录了，第二个用户未注销不能登录
        // http.sessionManagement().sessionAuthenticationStrategy(sessionRegistry)
        //        .expiredUrl("/login.html?22");
        //单处登录
        //http.sessionManagement().invalidSessionUrl("/loginPage").sessionAuthenticationFailureHandler(authenticationFailureHandler).maximumSessions(1);
        http.sessionManagement().sessionAuthenticationFailureHandler(authenticationFailureHandler).maximumSessions(1);
        http.csrf().disable().

                httpBasic().authenticationEntryPoint(authenticationEntryPoint)

                .and()
                .authorizeRequests()
                .antMatchers("/favicon.ico", "/css/**", "/js/**/**/*", "/fonts/**", "/layui/**", "/img/**",
                        "/v2/api-docs/**", "/swagger-resources/**", "/webjars/**", "/pages/**", "/druid/**",
                        "/statics/**").permitAll()

                .anyRequest()
                .authenticated()// 其他 url 需要身份认证
                //这是个很啃爹的问题 原本html方便的 可惜本人前台台low 然后用模板 默认登录页走控制器
                .and()
                .formLogin()  //开启登录
                .loginPage("/loginPage")
                .loginProcessingUrl("/user/login")
                .successHandler(authenticationSuccessHandler) // 登录成功
                .failureHandler(authenticationFailureHandler) // 登录失败
                .permitAll()

                .and()
                .logout()
                .logoutUrl("/user/logout")
                .logoutSuccessUrl("/login.html")
                .deleteCookies("JESSIONID")

                .and()
                .logout()
                .logoutSuccessHandler(logoutSuccessHandler)
                .permitAll()

                .and()
                .headers().frameOptions().disable();

        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(securityUserAuthor).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public static void main(String[] args) {


        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode("e10adc3949ba59abbe56e057f20f883e");
        System.out.println(encodedPassword);
    }
}
